package com.beemans.common.app.ui.fragments

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import com.beemans.common.app.R
import com.beemans.common.app.databinding.FragmentLocationBinding
import com.beemans.common.app.ui.base.BaseFragment
import com.beemans.common.utils.LocationUtils
import com.beemans.common.utils.PermissionHelper
import com.beemans.common.utils.TelephoneUtils
import com.blankj.utilcode.util.SpanUtils
import com.hjq.permissions.Permission
import com.tiamosu.databinding.delegate.lazyDataBinding
import com.tiamosu.databinding.page.DataBindingConfig
import com.tiamosu.fly.ext.clickNoRepeat

/**
 * @author tiamosu
 * @date 2021/8/11.
 */
class LocationFragment : BaseFragment() {
    private val dataBinding: FragmentLocationBinding by lazyDataBinding()

    private var title: String? = null
    private var updateCount = 0

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(R.layout.fragment_location)
    }

    override fun initParameters(bundle: Bundle?) {
        title = getString(MainFragment.PARAM_TITLE)
    }

    override fun initView(rootView: View?) {
        dataBinding.locationTitleBar.setTvTitle { text = title }
    }

    override fun initEvent() {
        dataBinding.locationBtnGet.clickNoRepeat {
            getLocation()
        }
    }

    /**
     * 获取位置信息
     */
    @SuppressLint("MissingPermission")
    private fun getLocation() {
        updateCount = 0
        if (!TelephoneUtils.isLocServiceEnable()) {
            showToast("请打开位置信息服务")
            return
        }
        PermissionHelper.with(this)
            .permission(Permission.ACCESS_COARSE_LOCATION, Permission.ACCESS_FINE_LOCATION)
            .onExplainRequestReason { true }
            .onForwardToSettings { true }
            .request { grantedList, _, _, _ ->
                if (grantedList.isNotEmpty()) {
                    LocationUtils.getLocation(onFailed = {
                        showToast("获取位置信息失败")
                    }, onSuccess = { _, address ->
                        showToast("位置信息更新成功")

                        updateCount++
                        SpanUtils.with(dataBinding.locationTvUpdateCount)
                            .append("更新次数：$updateCount")
                            .create()

                        SpanUtils.with(dataBinding.locationTvContent)
                            .append("位置信息:$address")
                            .create()
                    })
                }
            }
    }

    override fun doBusiness() {
    }
}